{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "9ed6894f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "0e9b8988",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the TEM image\n",
    "image = cv2.imread(\"18.35.22 CCD Acquire_1.jpg\", 0)\n",
    "\n",
    "# Threshold the image to convert it into binary\n",
    "threshold, binary_image = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY)\n",
    "\n",
    "# Find connected components in the binary image\n",
    "output = cv2.connectedComponentsWithStats(binary_image, 4, cv2.CV_32S)\n",
    "\n",
    "# Extract the number of connected components\n",
    "num_particles = output[0] - 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "51153853",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of particles: 37\n"
     ]
    }
   ],
   "source": [
    "# Print the number of particles\n",
    "print(\"Number of particles:\", num_particles)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "ab1633fb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Particle sizes: [987982      1      1      1      1      2      1      1      3      1\n",
      "      1      3      1      3      1      1     15      1      1     12\n",
      "      8      2      3      5      1      3      1      1      2      2\n",
      "      1      3      4      1      1      1      4]\n"
     ]
    }
   ],
   "source": [
    "# Threshold the image to convert it into binary\n",
    "threshold, binary_image = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY)\n",
    "\n",
    "# Find connected components in the binary image\n",
    "output = cv2.connectedComponentsWithStats(binary_image, 4, cv2.CV_32S)\n",
    "\n",
    "# Extract the number of connected components and the stats of each component\n",
    "num_particles, labels, stats, centroids = output\n",
    "\n",
    "# Get the particle sizes\n",
    "sizes = stats[1:, -1]\n",
    "\n",
    "# Print the sizes of the particles\n",
    "print(\"Particle sizes:\", sizes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1ef74e8c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
